<?php
namespace App\Http\Controllers\Order;

use App\Http\Controllers\Controller;
use App\Models\Agent\ChaoZongdai;
use App\Models\Log\ChaoMoneyLog;
use App\Models\Order\WxOrder;
use App\Models\Record\Record;
use App\Models\User\User;
use App\Models\WxPay\WxPayApi;
use App\Models\WxPay\WxPayOrderQuery;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WxOrderController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {

            $rows = $request->get("rows");

            $acc = WxOrder::join("users", "user_id", "=", "users.id")
                ->select(
                    "wx_orders.*",
                    DB::raw("wx_orders.id AS \"wx_orders.id\""),
                    "users.nickname");

            $acc = $this->filters($request, $acc);

            if($request->get("user_id")) {
                $acc = $acc->where("wx_orders.user_id", $request->get("user_id"));
            }
            if($request->get("status")) {
                $acc = $acc->where("wx_orders.status", $request->get("status"));
            }

//            $user_id = Auth::user()->user_id;

            $paginator = $acc->orderBy($request->get("sidx"), $request->get("sord"))->paginate($rows);

            $rows = [];
            foreach ($paginator as $page) {
                $page->money = $page->money / 100;
                $rows[] = $page;
            }

            $data = [
                "rows" => $rows,
                "total"=> $paginator->lastPage(),
                "page" => $paginator->currentPage(),
                "records" => $paginator->count(),
            ];

            return response()->json($data);

        } else {
            return view("order/wx/index");
        }
    }

    public function group(Request $request)
    {
        if ($request->ajax()) {
    
            $this->validate($request, [
                "begin_time" => "date",
                "end_time" => "date",
            ]);

            $date_func = "DATE_FORMAT(`create_time`,'%Y-%m-%d')";

            $begin_time = $request->get("begin_time");
            $end_time = $request->get("end_time");
    
            $orderBy = $request->get("sidx");
            
            if (!$begin_time) {
                $begin_time = "1970-01-01";
            }
    
            if (!$end_time) {
                $end_time = date("Y-m-d") . " 23:59:59";
            } else {
                $end_time = $end_time . " 23:59:59";
            }

            $acc = WxOrder::select(
                 DB::raw("DATE_FORMAT(`create_time`,'%Y-%m-%d') AS `date`"),              
                 DB::raw("SUM(money) AS \"SUM(money)\""),
                 DB::raw("COUNT(1) AS \"COUNT(1)\""))
                 ->where("status", 2)
             ->whereBetween("create_time", [$begin_time, $end_time]);

            $acc = $acc->groupBy(DB::raw($date_func));

            $paginator = $acc->orderBy(DB::raw($date_func), $request->get("sord"))->paginate($rows = $request->get("rows"));

            $t = 0;
            $rows = [];
            $sum = WxOrder::where("status", 2)->whereBetween("create_time", [$begin_time, $end_time])->sum("money");
            foreach ($paginator as $page) {

                $s = "SUM(money)";
                $t += $page->$s;

                $page->t = $t;
                $page->sum = $sum;
                $houtai = Record::where('type',4)->whereBetween("create_time",[$page->date,$page->date." 23:59:59"])->sum("money");
                $page->houtai = $houtai/100;
                $rows[] = $page;
            }

            $data = [
                "rows" => $rows,
                "total"=> $paginator->lastPage(),
                "page" => $paginator->currentPage(),
                "records" => $paginator->count(),
            ];

            return response()->json($data);

        } else {

            return view("order/wx/group", ["count" => WxOrder::count()]);
        }
    }

    public function check(Request $request)
    {
        $this->validate($request, [
            "id" => "int",
        ]);

        $orderId = $request->get("id");

        $order = WxOrder::find($orderId);

        $ret = [];
        if ($order->status != 2) {
            $input = new WxPayOrderQuery();
            $input->SetOut_trade_no($orderId);
            $ret = WxPayApi::orderQuery($input);

            if ($ret["trade_state"] && $ret["trade_state"] == "SUCCESS") {

                DB::beginTransaction();
                $order = WxOrder::find($orderId);
                if ($order->status != 2) {
                    $order->status = 2;
                    $order->finish_time = date("Y-m-d H:i:s");
                    $order->save();

                    $user = User::find($order->user_id);
                    $before = $user->money;
                    $user->money += $order->money;
                    $user->save();

                    $record = new Record();
                    $record->user_id = $user->id;
                    $record->before  = $before;
                    $record->after   = $user->money;
                    $record->money   = $order->money;
                    $record->detail  = "充值";
                    $record->type    =  2;
                    $record->create_time = date("Y-m-d H:i:s");
                    $record->save();

                    DB::commit();

                    try {
                        $tongdaofei = 2;
                        if ($user->zongdai) {

                            $zongdai = User::find($user->zongdai);

                            $fentan = $order->money * (int)$tongdaofei * $zongdai->zong_ratio / 100 / 100;
                            if ($fentan >= 1) {
                                $old = $zongdai->money;
                                if ($old > 0) {
                                    $zongdai->money -= $fentan;
                                    if ($zongdai->money < 0) {
                                        $zongdai->money = 0;
                                    }
                                    $zongdai->save();

                                    $record = new Record();
                                    $record->user_id = $zongdai->id;
                                    $record->before = $old;
                                    $record->after = $zongdai->money;
                                    $record->money = $record->after - $record->before;
                                    $record->detail = "通道费";
                                    $record->type = 9;
                                    $record->create_time = date("Y-m-d H:i:s");
                                    $record->save();
                                }
                            }

                            $chaoZongfentan = $order->money * (int)$tongdaofei * (100 - $zongdai->zong_ratio) / 100 / 100;
                            if ($chaoZongfentan >= 1) {

                                $chaoZongdai = ChaoZongdai::find($user->chao_zongdai);

                                $old = $chaoZongdai->money;
                                if ($old > 0) {
                                    $chaoZongdai->money -= $chaoZongfentan;
                                    if ($chaoZongdai->money < 0) {
                                        $chaoZongdai->money = 0;
                                    }

                                    $chaoZongdai->save();

                                    $chaoMoneyLog = new ChaoMoneyLog();
                                    $chaoMoneyLog->chao_zongdai = $chaoZongdai->id;
                                    $chaoMoneyLog->before  = $old;
                                    $chaoMoneyLog->after   = $chaoZongdai->money;
                                    $chaoMoneyLog->money   = $chaoMoneyLog->after -  $chaoMoneyLog->before;
                                    $chaoMoneyLog->detail  = "通道费";
                                    $chaoMoneyLog->create_time = date("Y-m-d H:i:s");
                                    $chaoMoneyLog->save();
                                }
                            }
                        }
                    } catch (\Exception $e) {
                    }
                }

                return response()->json(["success" => true , "ret" => $ret]);
            }
        }

        return response()->json(["success" => false , "ret" => $ret]);
    }
}
